import axios from 'axios';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus';
import EST_ENV from '@/config/env.js';
import * as Utils from '@/utils';

class HttpService {
  constructor() {
    this.timeout = 5 * 60 * 1000;
    if (!EST_ENV.getEnv()) EST_ENV.initEnvData();

    this.baseApiUrl = EST_ENV.getEnv().apiPath;
  }

  showLoading() {
    this.loadingInstance = ElLoading.service({
      lock: true,
      fullscreen: true,
    });
    console.log('showLoading');
  }

  closeLoading() {
    this.loadingInstance.close();
  }

  getHeaders(contentType) {
    return {
      Authorization: '',
      'Content-type': contentType || 'application/json;charset=utf-8',
      Token: localStorage.getItem('token') || '',
      Rejectunauthorized: false,
    };
  }

  responseError(data) {
    const message = data.message || data.msg || '小主，我有点累，请稍后再试';
    if (['0007'].includes(data.code)) {
      ElMessageBox.alert(message, '温馨提示', {
        center: true,
        confirmButtonText: '我知道了',
        callback: action => {
          router.push({
            path: '/login',
          });
        },
      });
    } else {
      ElMessage.error(message);
    }
  }
  // get
  get(path, data, config = { showLoading: false }) {
    if (config.showLoading) this.showLoading();
    return new Promise((resolve, reject) => {
      axios({
        method: 'get',
        headers: { ...this.getHeaders('application/x-www-form-urlencoded') },
        url: `${this.baseApiUrl}${this.getContext()}${path}?${Utils.qsString(data)}`,
      })
        .then(response => {
          if (response.data?.code == '200') {
            resolve(response.data || {});
          } else {
            this.responseError(response.data);
            reject({});
          }
        })
        .catch(error => {
          ElMessageBox.alert('小主，我有点累，请稍后再试', '异常提示', {
            center: true,
            confirmButtonText: '确定',
          });
          reject(error || {});
        })
        .finally(() => {
          if (config.showLoading) this.closeLoading();
        });
    });
  }
  // post
  post(path, data, config = { showLoading: false }) {
    if (config.showLoading) this.showLoading();
    return new Promise((resolve, reject) => {
      axios({
        timeout: this.timeout,
        method: 'post',
        headers: { ...this.getHeaders() },
        url: `${this.baseApiUrl}${this.getContext()}${path}`,
        data: data,
      })
        .then(response => {
          if (response.data?.code == '200') {
            resolve(response.data || {});
          } else {
            this.responseError(response.data);
            reject({});
          }
        })
        .catch(error => {
          console.log(error);
          ElMessageBox.alert('小主，我有点累，请稍后再试', '异常提示', {
            center: true,
            confirmButtonText: '确定',
          });
          reject(error || {});
        })
        .finally(() => {
          if (config.showLoading) this.closeLoading();
        });
    });
  }
  // 上传
  upload(path, data, config = { showLoading: false }) {
    if (config.showLoading) this.showLoading();
    return new Promise((resolve, reject) => {
      const formData = new FormData();
      Object.keys(data).map(k => {
        formData.append(k, data[k]);
      });
      axios({
        timeout: this.timeout,
        method: 'post',
        headers: { ...this.getHeaders('multipart/form-data') },
        url: `${this.baseApiUrl}${this.getContext()}${path}`,
        data: formData,
      })
        .then(response => {
          if (response.data?.code == '200') {
            resolve(response.data || {});
          } else {
            this.responseError(
              { code: '0001', data: {}, message: '小主，我有点累，请稍后再试' } || {},
            );
            reject({});
          }
        })
        .catch(error => {
          ElMessageBox.alert('小主，我有点累，请稍后再试', '异常提示', {
            center: true,
            confirmButtonText: '确定',
          });
          resolve({ code: '0001', data: {}, message: '执行失败' } || {});
        })
        .finally(() => {
          if (config.showLoading) this.closeLoading();
        });
    });
  }
  //获取接口上下文
  getContext() {
    if (EST_ENV.getEnv().env !== 'dev') {
      return '';
    }
    return '/api';
  }
}

export default new HttpService();
